package com.yzr.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * @description
 * @author: yzr
 * @date: 2021/10/18 17:41
 **/
@Slf4j
public class IOUtil {

    /**
     * 拷贝
     *
     * @param inputStream  输入
     * @param outputStream 写出
     */
    public static void copy(InputStream inputStream, OutputStream outputStream) {
        byte[] bytes = new byte[1024];
        int readLength;

        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
            while ((readLength = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, readLength);
            }
        } catch (IOException e) {
            log.error("文件拷贝异常：{}", e.getMessage());
        }
    }


    /***
     * 读取
     * @param in input
     * @return String
     */
    public static String read(InputStream in) {
        StringBuilder builder = new StringBuilder();
        try (InputStreamReader input = new InputStreamReader(in, "gbk")) {
            char[] readArr = new char[2048];
            int readLength = 0;
            while ((readLength = input.read(readArr)) != -1) {
                builder.append(readArr, 0, readLength);
            }
        } catch (IOException e) {
            log.error("读取异常：{}", e.getMessage());
        }
        return String.valueOf(builder);
    }


}
